import pickle
import base64
from django_redis import get_redis_connection

def merge_cart_cookie_to_redis(request, user, response):
    cookie_str = request.COOKIES.get('cart')
    if cookie_str is not None:
        cookie_cart = pickle.loads(base64.b64decode(cookie_str.encode()))
        redis_conn = get_redis_connection('cart')
        redis_cart = redis_conn.hgetall('cart_%s' %user.id)
        cart = {}
        for sku_id,count in redis_cart.items():
            cart[int(sku_id)] = int(count)

        selected_sku_id_list = []
        for sku_id,selected_count_dict in cookie_cart.items():
            cart[sku_id] = selected_count_dict['count']
            if selected_count_dict['selected']:
                selected_sku_id_list.append(sku_id)

        pl = redis_conn.pipeline()
        pl.hmset('cart_%s'%user.id,cart)
        pl.sadd('cart_selected_%s'%user,*selected_sku_id_list)
        pl.execute()
        response.delete_cookie('cart')
        return response
    else:
        return response
